//
//  ForgetPasswordControllerViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/12/14.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "ForgetPasswordControllerViewController.h"
#import "SetNewPasswodController.h"

@interface ForgetPasswordControllerViewController ()

@property (weak, nonatomic) IBOutlet UITextField *numTf;
@property (weak, nonatomic) IBOutlet UITextField *verificationcodeTf;
@property (weak, nonatomic) IBOutlet UIButton *verificationcodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (assign, nonatomic) NSInteger timeNmum;
@property (strong, nonatomic) NSTimer *getTime;
@end

@implementation ForgetPasswordControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //绑定手机号
    if (self.isBinding) {
        [self.nextBtn setTitle:@"提交" forState:UIControlStateNormal];
    }
    if (self.number) {
        self.numTf.text = self.number;
    }
}
- (IBAction)getVerificationcode:(id)sender {
    if((![self valiMobile:_numTf.text])|(_numTf.text.length == 0)){
        [self.view Message:@"请输入正确手机号" HiddenAfterDelay:1];
        return;
    }
    
    _verificationcodeBtn.enabled = NO;
    _timeNmum = 60;
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str = [formater stringFromDate:[NSDate date]];
    
    NSDictionary *parameters = @{@"login_id":_numTf.text,@"phone":_numTf.text,@"update_time":str};
    
    [MyAFN POST:GETVERFICATIONCODE parameters:parameters block:^(id responseObject) {
        NSDictionary *dic = responseObject;
        _verificationcodeBtn.enabled = YES;
        
        if ([[dic objectForKey:@"status"]integerValue]) {
            _getTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(begainTime) userInfo:nil repeats:YES];
        }else{
            [self.view Message:[dic objectForKey:@"msg"] HiddenAfterDelay:1];
        }
    }error:^(NSError *error) {
        
        _verificationcodeBtn.enabled = YES;
    }fromController:nil];

}

- (void)begainTime
{
    if (_timeNmum > 0) {
        _timeNmum--;
        [_verificationcodeBtn setTitle:[NSString stringWithFormat:@"%ldS",(long)_timeNmum] forState:UIControlStateNormal];
        _verificationcodeBtn.enabled = NO;
    }else{
        _timeNmum = 0;
        if ([_getTime isValid]) {
            [_getTime invalidate];
            _getTime = nil;
        }
        [_verificationcodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        _verificationcodeBtn.enabled = YES;
    }
    
}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self checkVerificationcode];
}

- (void)checkVerificationcode
{
    if (_verificationcodeTf.text.length != 4) {
        [self.view Message:@"请输入4位验证码" HiddenAfterDelay:1];
    }else{
        if(!_numTf.text.length){
            
            [self.view Message:@"请输入手机号" HiddenAfterDelay:1];
            return;
        }
        NSDictionary *parameters = @{@"phone":_numTf.text,@"send_code":_verificationcodeTf.text};
        [MyAFN POST:CHECKVERFICATIONCODE parameters:parameters block:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
            if (![[dic objectForKey:@"status"]integerValue]) {
                
                [self performSelector:@selector(message) withObject:nil afterDelay:0.5];
                
                
              
            }else{

            }
        }error:^(NSError *error) {
            
        }fromController:self];
    }
}

- (void)message
{
    [self.view Message:@"验证码有误" HiddenAfterDelay:1];
}

- (IBAction)setNewPassword:(UIButton *)sender {
    
    if (_verificationcodeTf.text.length != 4) {
        [self.view Message:@"请输入4位验证码" HiddenAfterDelay:1];
    }else{
        if(!_numTf.text.length){
            
            [self.view Message:@"请输入手机号" HiddenAfterDelay:1];
            return;
        }
        
        NSDictionary *parameters = @{@"phone":_numTf.text,@"send_code":_verificationcodeTf.text};
        [MyAFN POST:CHECKVERFICATIONCODE parameters:parameters block:^(id responseObject) {
            
            NSLog(@"%@",[responseObject objectForKey:@"msg"]);
            NSDictionary *dic = responseObject;
            
            if (![[dic objectForKey:@"status"]integerValue]) {
                
                [self performSelector:@selector(haveError) withObject:nil afterDelay:0.5];
            }else{
                
                if (self.isBinding) {
                    //绑定手机号
                    [self bindNum];
                }else{
                    //忘记密码
                    [self forgetPwd];
                }
                
                
            }
        }error:^(NSError *error) {
            
        }fromController:self];
        
        
        
        
    }
    
}

- (void)bindNum
{
    NSDictionary *parameter = @{@"login_id":_numTf.text,@"uuid":_uuid};
    [MyAFN POST:BOUNDUSER parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            if (self.bound) {
                self.bound(_numTf.text);
            }
            
            [Myuser sharedUser].login_id = _numTf.text;
            [[NSUserDefaults standardUserDefaults]setObject:_numTf.text forKey:@"userid"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            
            [self performSelector:@selector(showMsg:) withObject:[response objectForKey:@"msg"] afterDelay:0.5];
            
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
}

- (void)showMsg:(NSString *)msg
{
    [self.view Message:msg HiddenAfterDelay:1];
}

- (void)forgetPwd
{
    SetNewPasswodController *setNewPassword = [[SetNewPasswodController alloc]init];
    
    setNewPassword.number = _numTf.text;
    [self.navigationController pushViewController:setNewPassword animated:YES];
}

- (void)haveError
{
[self.view Message:@"错误,请确认信息填写正确" HiddenAfterDelay:1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
